package com.ruoyi.common.utils.zfb;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.ruoyi.common.core.domain.DTO.TradeAppPayBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Value;

@Slf4j
@Component
public class AlipayTradeAppPay {

    @Value("${alipay.app.server-url}")
    private String serverUrl;

    @Value("${alipay.app.app-id}")
    private String appId;

    @Value("${alipay.app.private-key}")
    private String privateKey;

    @Value("${alipay.app.notify-url}")
    private String notifyUrl;

    @Value("${alipay.app.alipay-cert-public-key}")
    private String alipayCertPublicKey;

    @Value("${alipay.app.app-cert-public-key}")
    private String appCertPublicKey;

    @Value("${alipay.app.alipay-root-cert}")
    private String rootCertPath;

    public AlipayTradeAppPayResponse tradeAppPay(TradeAppPayBO tradeAppPayBO) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig(privateKey, appId, serverUrl, alipayCertPublicKey, appCertPublicKey, rootCertPath));

        // 构造请求参数以调用接口
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

        // 设置商户订单号
        model.setOutTradeNo(tradeAppPayBO.getOrderNo());
        BigDecimal totalAmount = tradeAppPayBO.getTotalAmount();
        DecimalFormat df = new DecimalFormat("0.00");
        String totalAmountStr = df.format(totalAmount);
        // 设置订单总金额
        model.setTotalAmount(totalAmountStr);
        // 设置订单标题
        model.setSubject(tradeAppPayBO.getSubject());
        // 1. 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 2. 当前时间 + 10 分钟
        LocalDateTime futureTime = now.plusMinutes(10);
        // 3. 格式化输出（可选）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = futureTime.format(formatter);
        // 设置订单绝对超时时间
        model.setTimeExpire(formattedTime);
        request.setBizModel(model);
        log.info("支付宝app支付订单参数订单号={},金额={},过期时间={}", model.getOutTradeNo(), model.getTotalAmount(), model.getTimeExpire());
        //设置回调地址
        request.setNotifyUrl(notifyUrl);

        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        String orderStr = response.getBody();

        log.info("支付宝app支付响应订单信息={}", orderStr);

        if (response.isSuccess()) {
            log.info("APP支付调用成功");
        } else {
            log.info("APP支付调用失败");
        }
        return response;
    }

    private static AlipayConfig getAlipayConfig(String privateKey, String alipayPublicKey, String appId, String serverUrl) {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(serverUrl);
        alipayConfig.setAppId(appId);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    private static AlipayConfig getAlipayConfig(String privateKey, String appId, String serverUrl, String alipayCertPublicKey, String appCertPublicKey, String rootCertPath) {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setServerUrl(serverUrl);
        alipayConfig.setAppId(appId);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        alipayConfig.setFormat("json");
        alipayConfig.setAppCertPath(appCertPublicKey);
        alipayConfig.setAlipayPublicCertPath(alipayCertPublicKey);
        alipayConfig.setRootCertPath(rootCertPath);
        return alipayConfig;
    }
}